<?php


namespace app\common\helper;

use Elasticsearch\ClientBuilder as ESClientBuilder;
use think\facade\Env;

class ElasticSearch
{
    protected $es;

    protected $config = [
        'hosts' => [
            //'8.129.67.215:9200',
            '127.0.0.1:9200',
            //'172.27.163.122:9200'
        ],
        'username' => 'elastic',
        'password' => 'goeW8L8f69Cws91s'
    ];

    public function __construct()
    {
        return $this->es = $this->init();
    }

    protected function init()
    {
        // 从配置文件读取 Elasticsearch 服务器列表
        $builder = ESClientBuilder::create()
            ->setHosts($this->config['hosts'])
            ->setBasicAuthentication($this->config['username'], $this->config['password']);

        // 应用调试模式
        if (config('app_debug') === 'true') {
            // 配置日志，Elasticsearch 的请求和返回数据将打印到日志文件中，方便我们调试
            $builder->setLogger(app('log')->error());
        }

        return $builder->build();
    }

    /**
     * @Notes: es 信息
     * @return array
     * @author: ts
     * @Time: 2020/4/6 10:51
     */
    public function info()
    {
        return $this->es->info();
    }

    // 创建索引
    public function index($name, $mappings)
    {
        $params = [
            'index' => $name,
            'body' => [
                'settings' => [
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0,
                ],
                'mappings' => [
                    'properties' => $mappings
                ]
            ]
        ];

        return $this->es->indices()->create($params);
    }

    // Set the index and type
    public function putMapping($name, $data)
    {
        $params = [
            'index' => $name,
            'body' => [
                '_source' => [
                    'enabled' => true
                ],
                'properties' => $data
            ]
        ];

        return $this->es->indices()->putMapping($params);
    }

    // 获取 getMapping
    public function getMapping($name)
    {
        $params = ['index' => $name];
        return $this->es->indices()->getMapping($params);
    }

    // 统计数量
    public function getDocCount($name)
    {
        $params = ['index' => $name];
        return $this->es->count($params);
    }

    /**
     * @Notes:
     * @param $name 索引名称
     * @param $id 文档编号
     * @author: ts
     * @Time: 2020/4/6 10:59
     */
    public function getIndex($name, $id)
    {
        return $this->es->get(['index' => $name, 'id' => $id]);
    }

    /**
     * @Notes: 删除索引
     * @param $name
     * @return array
     * @author: ts
     * @Time: 2020/4/6 11:31
     */
    public function deleteIndex($name)
    {
        return $this->es->indices()->delete(['index' => $name]);
    }

    // // Document will be indexed to my_index/_doc/my_id
    public function createDoc($name, $data)
    {
        $params = [
            'index' => $name,
            'id' => $data['id'],
            'body' => $data
        ];
        $response = $this->es->index($params);
    }


    /**
     * @Notes: 更新文档
     * @param $index 索引
     * @param $id 文档 id
     * @param $data 内容
     * @author: ts
     * @Time: 2020/4/21 9:51
     */
    public function updateDoc($index, $id, array $data)
    {
        $params = [
            'index' => $index,
            'id' => $id,
            'type' => '_doc',
            'body' => [
                'doc' => $data
            ]
        ];

        $this->es->update($params);
    }

    // 删除一个文档
    public function delDoc($param)
    {
        $this->es->delete($param);
    }

    // 批量创建文档
    public function bulk($params)
    {
        return $this->es->bulk($params);
    }

    // 搜索
    public function queryData($indexName, $kye, $sort, $from = 0, $size = 10)
    {
        $from = $from * $size;
        //$indexName = Env::get('elasticsearch.goods_index') ?? 'products';

        $params = [
            'index' => $indexName,
            'client' => [
                'timeout' => 10,        // ten second timeout
                'connect_timeout' => 10
            ],
            'body' => [
                'from' => $from,
                'size' => $size,
                'query' => [
                    'bool' => [
                        'should' => [
                            [
                                'multi_match' => [
                                    'query' => $kye,
                                    'fields' => [
                                        'goods_name^2',
                                        'single_goods_name'
                                    ],
                                ],
                            ],
                            [
                                'wildcard' => [
                                    'single_goods_name' => "$kye*"
                                ]
                            ],
                            [
                                'fuzzy' => [
                                    'single_goods_name' => [
                                        'value' => $kye
                                    ]
                                ]
                            ]
                        ],
                    ],
                ],
                'sort' => [
                    ['_score' => "desc"],
                    ['goods_sort' => 'desc']
                ],
            ]
        ];

        return $this->es->search($params);
    }

    // 查看分词结果
    public function getAnalyze($param)
    {
        return $this->es->indices()->analyze($param);
    }

    // 搜索
    public function search($param)
    {
        return $this->es->search($param);
    }

}
